<?php
/**
 * 兑换记录
 */

namespace app\api\model;


use app\common\model\Model;
use think\Db;

class ExchangeRecord extends Model
{
    const TABLE_NAME = 'exchange_record';
    const CACHE_EXPIRE_LEVEL = self::CACHE_EXPIRE_LEVEL_4;

    protected $name = self::TABLE_NAME;

    public static function isUserExchangePrize($user_id,$prize_id)
    {
        $info = self::commonQuery(self::TABLE_NAME)
              ->where(['record_user_id'=>$user_id,'record_prize_id'=>$prize_id])
              ->find();
        return !empty($info);
    }
    public static function addRecord($user_id,$prize_id,$points)
    {
        return self::commonQuery(self::TABLE_NAME)
              ->insert([
                  'record_user_id'=>$user_id,
                  'record_prize_id'=>$prize_id,
                  'record_points'=>$points,
                  'record_time'=>time()
              ],false,true);
    }
    public static function getRecordInfo($record_id)
    {
        return  self::commonQuery(self::TABLE_NAME,self::CACHE_EXPIRE_LEVEL)
            ->where(['record_id'=>$record_id])
            ->find();
    }
    //兑换奖品 扣除 用户积分 和添加 积分记录
   public static function handleExchangePrize($user_id,$prize_id,$points)
   {
       Db::startTrans();

       try{
           $user_points = User::getUserPointsForUpdate($user_id);
           if($user_points < $points)
           {
               Db::rollback();
               return ['status'=>false,'msg'=>'积分不足'];
           }
           User::descUserPoints($user_id,$points);
           $record_id = self::addRecord($user_id,$prize_id,$points);
           PointsRecord::addRecord($user_id,PointsRecord::POINTS_EXCHANGE,$record_id,$points);
       }catch (\Exception $e)
       {
           Db::rollback();
           return ['status'=>false,'msg'=>$e->getMessage()];
       }
       Db::commit();
       return ['status'=>true,'msg'=>''];
   }
}